package com.atguigu.spzx.user.service.impl;

import com.atguigu.spzx.common.util.AuthUtil;
import com.atguigu.spzx.model.entity.user.Region;
import com.atguigu.spzx.model.entity.user.UserAddress;
import com.atguigu.spzx.user.mapper.UserAddressMapper;
import com.atguigu.spzx.user.service.RegionService;
import com.atguigu.spzx.user.service.UserAddressService;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

@Service
public class UserAddressServiceImpl extends ServiceImpl<UserAddressMapper , UserAddress> implements UserAddressService {
    @Resource
    RegionService regionService;
    @Override
    public void saveUserAddress(UserAddress userAddress) {
        //如果新增的地址 是默认的，需要先更新其他所有地址为非默认
        if(userAddress.getIsDefault().intValue()==1){
            this.update(Wrappers.lambdaUpdate(UserAddress.class)
                    .set(UserAddress::getIsDefault , 0)
                    .eq(UserAddress::getUserId , AuthUtil.getUserInfo().getId())
                    .eq(UserAddress::getIsDefault , 1));
        }
        //手动设置必须的参数
        userAddress.setUserId(AuthUtil.getUserInfo().getId());

        String provinceCode = userAddress.getProvinceCode();
        String cityCode = userAddress.getCityCode();
        String districtCode = userAddress.getDistrictCode();
        //code值是 省市区存在表中的数值的code码  需要转为省市区标题名称才可以拼接地址
        Region provinceRegion = regionService.getOne(Wrappers.lambdaQuery(Region.class)
                .eq(Region::getCode, provinceCode));
        Region cityRegion = regionService.getOne(Wrappers.lambdaQuery(Region.class)
                .eq(Region::getCode, cityCode));
        Region districtRegion = regionService.getOne(Wrappers.lambdaQuery(Region.class)
                .eq(Region::getCode, districtCode));
        String address = userAddress.getAddress();
        userAddress.setFullAddress(provinceRegion.getName()+ cityRegion.getName()
                +districtRegion.getName() + " "+ address);
        this.save(userAddress);
    }
}
